import React, { useState, useContext, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { UploadContext } from '../uploadContext';

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('上传头像的格式只能是jpg/png!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('头像大小必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const Uptou = () => {
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const { startUpload, endUpload } = useContext(UploadContext);

    const [userInfo, setUserInfo] = useState(null); // 初始值为null，表示没有用户信息
    useEffect(() => {
        const userInfoString = localStorage.getItem('user');
        if (userInfoString) {
            try {
                const parsedUserInfo = JSON.parse(userInfoString);
                setUserInfo(parsedUserInfo); // 设置userInfo状态为用户信息对象
                setImageUrl(parsedUserInfo.tou_img); // 设置imageUrl为用户头像
            } catch (error) {
                console.error('Error parsing user info from localStorage:', error);
                // 清除localStorage中的用户信息或进行其他错误处理
                localStorage.removeItem('userInfo');
            }
        }
    }, []); // 空数组表示这个effect只在组件初次渲染时运行

    const handleChange = (info) => {
        console.log(info.file.status);

        if (info.file.status === 'uploading') {
            getBase64(info.file.originFileObj, (url) => {
                setImageUrl(url); // 设置组件内的imageUrl状态

                // 更新userInfo的tou_img属性，并同步到localStorage
                if (userInfo) {
                    const updatedUserInfo = { ...userInfo, tou_img: url };
                    setUserInfo(updatedUserInfo); // 更新userInfo状态
                    localStorage.setItem('user', JSON.stringify(updatedUserInfo)); // 同步更新localStorage
                }
                setLoading(false);
                endUpload(); // 调用结束上传的context方法
            });
        } else if (info.file.status === 'error') {
            setLoading(false); // 上传错误，设置加载状态为 false
            console.error('头像上传失败:', info.file.response);
            message.error('头像上传失败，请重试！'); // 显示错误消息
        }
    };

    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                上传头像
            </div>
        </button>
    );

    return (
        <ImgCrop modalOk={'完成'} modalCancel={'取消'} rotationSlider>
            <Upload
                name="avatar"
                listType="picture-circle"
                className="avatar-uploader"
                showUploadList={false}
                action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl ? (
                    <img
                        src={imageUrl}
                        alt="avatar"
                        style={{
                            width: '100%',
                            borderRadius: '50%',
                        }}
                    />
                ) : (
                    uploadButton
                )}
            </Upload>
        </ImgCrop>
    );
};

export default Uptou;
